<template>
	<view class="pageBox">
		<!--发布视频-->

		<view class="padding-bj flex">
			<view class="upload radius-bock">
				
				<view v-if="video.tempFilePath" @tap="handleVideo">
					<!-- #ifdef APP-PLUS -->
					<video class="radius-bock" :controls="false" :show-center-play-btn="false" :src="video.tempFilePath" object-fit="fill" autoplay muted/>
					<!-- #endif -->
					
					<!-- #ifndef APP-PLUS -->
					<video class="radius-bock" :controls="false" :show-center-play-btn="false" :src="video.tempFilePath" object-fit="cover" />
					<!-- #endif -->
				</view>
				
				<block v-else>
					<view v-if="video.progress === 0 && video.progress !== 100" class="text-lg text-gray text-center" @tap="handleVideo">
						<!-- <u-icon name="plus"></u-icon> -->
						<text class="wlIcon-tianjia"></text>
						<view class="margin-top-xs text-sm">添加视频</view>
					</view>
				</block>
				
				<view v-if="video.progress > 0 && video.progress !== 100" class="loading flex align-center justify-center">
					<view class="text-xxl text-gray text-center">
						<view class="margin-top-xs text-min">
							{{conver(video.totalBytesSent, false)}}/{{conver(video.totalBytesExpectedToSend)}}
						</view>
					</view>
				</view>
			</view>
			
			<editor
				id="editor"
				@ready="onEditorReady"
				@input="onEditorInput"
				placeholder="视频标题"
			/>
			
		</view>
		
		<!-- 底部 -->
		<view class="safeAreaBottom"></view>
		
		<view>
			<view class="cu-bar tabbar foot flex flex-direction">
				<button class="cu-btn bg-red lg" @tap="handleSubmit">
					发布视频
				</button>
			</view>
		</view>
		
	</view>
</template>

<script>
import { BASE_URL, API_URL } from '@/env.js';
import { mapState, mapActions } from 'vuex';
	
export default {
	components: {
		
	},
	data() {
		return {
			video:{
				tempFilePath: null, // 本地缓存
				progress: 0, //上传进度
				totalBytesSent: 0, //已经上传的数据长度
				totalBytesExpectedToSend: 0, //预期需要上传的数据总长度
				url:'',
			},
			params: {
				content: '',
			},
			requestStatus : false, //请求状态，防止重复提交
		}
	},
	onLoad() {
		
	},
	onShow(){
		
	},
	methods: {
		conver (limit, unit = true) {
		    return (limit / (1024 * 1024)).toFixed(1) + (unit ? 'MB' : '');
		},
		guid (len = 32, firstU = true, radix = null){
			let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
			let uuid = [];
			radix = radix || chars.length;
		
			if (len) {
				// 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
				for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
			} else {
				let r;
				// rfc4122标准要求返回的uuid中,某些位为固定的字符
				uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
				uuid[14] = '4';
		
				for (let i = 0; i < 36; i++) {
					if (!uuid[i]) {
						r = 0 | Math.random() * 16;
						uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
					}
				}
			}
			// 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
			if (firstU) {
				uuid.shift();
				return 'u' + uuid.join('');
			} else {
				return uuid.join('');
			}
		},
		onEditorInput(e) {
			this.params.content = e.detail.html;
		},
		onEditorReady() {
			// #ifdef MP-BAIDU
			this.editorCtx = requireDynamicLib('editorLib').createEditorContext('editorId');
			// #endif
		
			// #ifdef APP-PLUS || H5 ||MP-WEIXIN
			uni.createSelectorQuery()
				.select('#editor')
				.context(res => {
					this.editorCtx = res.context;
				})
				.exec();
			// #endif
		},
		
		// 发布
		async handleSubmit() {
			const video = this.video;
			const params = this.params;
			
			// 判断视频是否上传完成
			if(video.tempFilePath === null){
				this.$wanlshop.msg('请上传视频');
				return;
			}else{
				if(video.progress === 0){
					this.$wanlshop.msg('异常请重开此页面');
					return;
				}
				if(video.progress < 100 || video.totalBytesSent !== video.totalBytesExpectedToSend){
					this.$wanlshop.msg('视频还没有上传完成哦~');
					return;
				}
			}
			
			if(!params.content){
				this.$wanlshop.msg('请编辑视频标题~');
				return;
			}
			
			// 请求完成前 按钮点击将不会继续执行此函数
			if(this.requestStatus){
				// 利用 return 终止函数继续运行
				return false;
			}
		
			this.requestStatus = true;
	
			uni.request({
				url: '/live/addvideo',
				data: {
					file: this.video.url,
					title: this.params.content,
				},
				success: res => {
					res = res.res;
					if (res.code === 1) {
						this.$wanlshop.msg('发布成功！');
						
						uni.redirectTo({
							url: '/pages/new/video-list'
						})
					}else{
						this.$wanlshop.msg('网络异常，请稍后在试');
					}
					
					this.requestStatus = false;
				}
			});
		},
		
		// 选择视频
		handleVideo(e) {
			let that = this;
			uni.chooseVideo({
				success: ch => {
					let name = ch.name ? ch.name : `${this.guid(12)}.mp4`;
					
					// uni.request({
					// 	url: '/wanlshop/video/getUploadProof',
					// 	data: {
					// 		name: name,
					// 	},
					// 	success: sts => {
					// 		const uploadTask = uni.uploadFile({
					// 			url: sts.data.ossUrl, 
					// 			filePath: ch.tempFilePath,
					// 			name: sts.data.file,
					// 			formData: sts.data.formData,
					// 			success: upload => {
					// 				if(upload.statusCode === 200){
					// 					this.video.url = res.data.url;
					// 					this.video.tempFilePath = ch.tempFilePath;
					// 				}else{
					// 					this.$wanlshop.msg("上传失败: "+res.msg);
					// 				}
					// 			},
					// 			fail: (res) => {
					// 				console.info(res);
					// 			}
					// 		});
					// 		uploadTask.onProgressUpdate((res) => {
					// 			this.video.progress = res.progress;
					// 			this.video.totalBytesSent = res.totalBytesSent;
					// 			this.video.totalBytesExpectedToSend = res.totalBytesExpectedToSend;
					// 		});
					// 	}
					// });
					
					const uploadTask =  uni.uploadFile({
						url: BASE_URL + "/api/common/upload",
						filePath: ch.tempFilePath,
						name: "file",
						header: { token: uni.getStorageSync("token") },
						success: res => {
							res = JSON.parse(res.data);
							console.log("res", res);
							if (res.code === 1) {
								console.log("fullurl", res.data.fullurl);
								this.video.tempFilePath = ch.tempFilePath;
								this.video.url = res.data.url;
								
							} else {
								that.$wanlshop.msg("上传失败: "+res.msg);
							}
						},
						complete: e => {
							uni.hideLoading();
						}
					});
					
					uploadTask.onProgressUpdate((res) => {
						this.video.progress = res.progress;
						this.video.totalBytesSent = res.totalBytesSent;
						this.video.totalBytesExpectedToSend = res.totalBytesExpectedToSend;
					});
					
				}
			});
		},
		
	}
}
</script>

<style scoped lang="scss">
.padding-bj {
	padding: 25rpx;
}
.upload {
	position: relative;
	width: 220rpx;
	height: 300rpx;
	margin-right: 25rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f0f0f0;
	color: #333333;
	
	video{
		width: 220rpx;
		height: 300rpx;
	}
	
	.loading{
		position: absolute;
		top: 0;
		bottom: 0;
		right: 0;
		left: 0;
	}
}

#editor {
	flex: 1;
	height: 240rpx;
	min-height: 100rpx;
}

.radius-bock {
	border-radius: 18rpx;
	overflow: hidden;
}
.safeAreaBottom {
    height: 106rpx;
    height: calc(env(safe-area-inset-bottom) + 106rpx);
    width: 100%;
}
.tabbar{
    z-index: 1;
    background-color: transparent !important;
}

.cu-bar.foot {
    position: fixed;
    width: 100%;
    bottom: 0;
    z-index: 1;
	box-shadow: 0 0px 0px rgba(0, 0, 0, 0) !important;
}

.tabbar .cu-btn{
    width: calc(100% - 52rpx);
    font-size: 34rpx;
    height: 80rpx;
}
.margin-top-xs {
	margin-top: 10rpx;
}
.text-min {
	font-size: 24rpx;
}
</style>